package com.youxuit.youxu.kecheng.SynchronizedDemo;

public class SyncronizedClassClass5 implements Runnable{

    public static SyncronizedClassClass5 block1 = new SyncronizedClassClass5();
    public static SyncronizedClassClass5 block2 = new SyncronizedClassClass5();


    @Override
    public void run() {
        methord();
    }

    private  void methord() {
        //用this时，两个任务分别拿的是各自的锁，所以是乱序执行
        //synchronized (this) {
        //用SyncronizedClassClass5.class时，不管多少个任务来，锁都是同一把，即统一时刻只会被一个线程执行
        synchronized (SyncronizedClassClass5.class) {
            System.out.println("我的线程名字是：" + Thread.currentThread().getName() + ",我开始运行了");

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {

            }
            System.out.println("我的线程名字是：" + Thread.currentThread().getName() + "，运行结束了");
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(block1, "t1");
        Thread t2 = new Thread(block2, "t2");
        t1.start();
        t2.start();

        while (t1.isAlive() || t2.isAlive()) {

        }
        System.out.println("finish");
    }
}
